import { defineStore } from "pinia";
import { getRtcDeviceList } from "@/api/core/rtcDevice";
import { callType } from "@/constant/callType";
import { markRaw } from "vue";
import { SocketWorker } from "@/socket/socketWorker";
import { device } from "@rongcloud/plugin-rtc";

const useCallStore = defineStore("call", {
  state: () => ({
    // Video - 视频, Audio - 音频, Both - 音视频
    callType: callType.Both.value,
    rtcDeviceMap: {},
    meetRecordId: "",
    meetRecordName: "",
    meetingUserIds: [],
    // idle - 空闲，可以接听通话。 calling - 正在呼叫。 onCall - 正在通话中
    callStatus: "idle",
    autoAnswer: false,
    socket: null,
    microphones: [],
    cameras: [],
    currentMicrophoneId: "",
    currentCameraId: "",
    resolution: "W1920_H1080",
  }),
  actions: {
    setCallType(callType) {
      console.log("call.js , setCallType", callType);
      this.callType = callType;
    },
    setMeetRecordId(meetRecordId) {
      console.log("1212", meetRecordId);

      this.meetRecordId = meetRecordId;
    },
    setMeetRecordName(meetRecordName) {
      this.meetRecordName = meetRecordName;
    },
    setMeetingUserIds(userIds) {
      this.meetingUserIds = userIds;
    },
    addMeetingUserId(userId) {
      this.meetingUserIds.push(userId);
    },
    removeMeetingUserId(userId) {
      this.meetingUserIds = this.meetingUserIds.filter(
        (item) => item !== userId
      );
    },
    setCallStatus(callStatus) {
      this.callStatus = callStatus;
    },
    setAutoAnswer(autoAnswer) {
      this.autoAnswer = autoAnswer;
    },
    setRtcDeviceStatus(rtcDevice) {
      const deviceList = this.rtcDeviceMap[rtcDevice.userId];
      for (const device of deviceList) {
        if (device.deviceType === rtcDevice.deviceType) {
          device.status = rtcDevice.status;
        }
      }
    },
    getRtcDeviceMap() {
      getRtcDeviceList().then((res) => {
        this.rtcDeviceMap = res.data;
      });
    },
    buildSocket() {
      this.socket = markRaw(
        new SocketWorker(`${import.meta.env.VITE_APP_WS_API}/socket`)
      );
      this.on("updateLocation", (data) => {
        const deviceList = this.rtcDeviceMap[data.userId];
        for (const device of deviceList) {
          device.latitude = data.latitude;
          device.longitude = data.longitude;
        }
      });
      this.on("updateBattery", (data) => {
        const deviceList = this.rtcDeviceMap[data.userId];
        for (const device of deviceList) {
          device.batteryLevel = data.level;
        }
      });
      this.on("online", (data) => {
        this.setRtcDeviceStatus(data);
      });
      this.on("offline", (data) => {
        this.setRtcDeviceStatus(data);
      });
    },
    connect() {
      if (!this.socket) {
        this.buildSocket();
      }
      return this.socket.connect();
    },
    on(event, callback) {
      if (!this.socket) {
        this.buildSocket();
      }
      this.socket.on(event, callback);
    },
    off(event) {
      if (this.socket) {
        this.socket.off(event);
      }
    },
    emit(event, data) {
      if (this.socket) {
        this.socket.emit(event, data);
      }
    },
    disconnect() {
      // return this.socket.disconnect()
    },
    async getMicrophoneAndCamera() {
      const microphones = await device.getMicrophones();
      if (microphones.length > 0) {
        this.currentMicrophoneId = microphones[0].deviceId;
      }
      this.microphones = microphones;

      const cameras = await device.getCameras();
      if (cameras.length > 0) {
        this.currentCameraId = cameras[0].deviceId;
      }
      this.cameras = cameras;
    },
    setMicrophoneId(microphoneId) {
      this.currentMicrophoneId = microphoneId;
    },
    setCameraId(cameraId) {
      this.currentCameraId = cameraId;
    },
  },
});

export default useCallStore;
